package priv.abadstring.study.haoke.webapi.manage;

import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import priv.abadstring.study.haoke.webapi.vo.image.ImageUploadVO;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

/**
 * ImageManage
 *
 * @author aBadString
 * @date 2021-06-15 17:46:09
 */
@Service("imageManageByFileSystem")
public class ImageManageByFileSystem implements ImageManage {

    /** 允许上传的格式 */
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
    public static final String IMAGE_ROOT_FOLDER = "D:\\Users\\aBadString\\Pictures\\haoke" + File.separator + "images";
    public static final String IMAGE_ROOT_URL = "http://localhost/image";

    @Override
    public ImageUploadVO upload(MultipartFile uploadFile) {
        // 对文件后缀名进行校验
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        if(!isLegal){
            return ImageUploadVO.builder()
                    .status("error")
                    .build();
        }

        try {
            // 文件新路径
            String fileName = uploadFile.getOriginalFilename();
            String filePath = getFilePath(fileName);
            // 生成图片的绝对引用地址
            String url = IMAGE_ROOT_URL + StringUtils.replace(
                    StringUtils.substringAfter(filePath, IMAGE_ROOT_FOLDER),
                    File.separator, "/"
            );

            // 写文件到磁盘
            uploadFile.transferTo(new File(filePath));
            return ImageUploadVO.builder()
                    .name(url)
                    .status("done")
                    .uid(String.valueOf(System.currentTimeMillis()))
                    .build();
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            return ImageUploadVO.builder()
                    .status("error")
                    .build();
        }
    }

    /**
     * 生成图片存储路径
     * @param sourceFileName 图片名
     */
    private String getFilePath(String sourceFileName) {
        Calendar calendar = Calendar.getInstance();
        int intYear = calendar.get(Calendar.YEAR);
        int intMonth = calendar.get(Calendar.MONTH) + 1;
        int intDay = calendar.get(Calendar.DATE);

        // yyyy/MM/dd
        String fileFolder = IMAGE_ROOT_FOLDER
                + File.separator + intYear
                + File.separator + intMonth
                + File.separator + intDay;
        File file = new File(fileFolder);
        if (!file.isDirectory()) {
            // 如果目录不存在，则创建目录
            file.mkdirs();
        }

        // 生成新的文件名
        String fileName = intYear + "_" + intMonth + "_" + intDay + "_"
                + RandomUtils.nextInt(100, 9999) + "."
                + StringUtils.substringAfterLast(sourceFileName, ".");
        return fileFolder + File.separator + fileName;
    }
}
